//
//  ViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/7/24.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher
import KRProgressHUD
import YJBannerView
import PPBadgeViewSwift
import Moya
import SwiftyJSON
import UIAlertController_Blocks
//import WZLBadge


class ViewController: BaseViewController, YJBannerViewDelegate, YJBannerViewDataSource, UITableViewDelegate, UITableViewDataSource  {
    
    var isCa:Bool = false
    var isRenZheng:Bool = false
    @IBOutlet weak var labelAmount: UILabel!
    
    @IBOutlet weak var labelAllAmount: UILabel!
    
    private var bulletinData: NSArray = []
    private var bannerData:NSArray = []
    @IBOutlet weak var adView: YJBannerView!
    
    @IBOutlet weak var tableView: UITableView!        
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "首页";
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.register(R.nib.homeTableViewCell(), forCellReuseIdentifier: "homeTableViewCell")
        adView.delegate = self
        adView.dataSource = self
        adView.placeholderImage = R.image.banner()
        adView.bannerViewSelectorString = "sd_setImageWithURL:placeholderImage:"
        
        
        // Do any additional setup after loading the view, typically from a nib.
        let bar = UIBarButtonItem(image: R.image.message(), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.openMessage(_:)))
        
        self.navigationItem.rightBarButtonItem = bar
        
//        self.navigationItem.rightBarButtonItem?.pp.addBadge(number: 1)
//        bar.setbarge
//        self.navigationItem.rightBarButtonItem?.showBadge(with: .number, value: 1, animationType: .none)
        
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        NetWorkRequest(.accountdetail()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                let formater = NumberFormatter()
                formater.numberStyle = .decimal
                formater.minimumFractionDigits = 2
                formater.maximumFractionDigits = 2
                self.labelAmount.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber(value:data["available_fund"].doubleValue / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()
                    .build()
                    .render(contentSizeCategory: .large)
                
                let c = data["frozen_trade_deposit"].doubleValue + data["frozen_perform_deposit"].doubleValue
                self.labelAllAmount.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber(value: c / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()
                    .build()
                    .render(contentSizeCategory: .large)
            } else if res["code"] as! String == "100008" {
                
            }
        }
        
        
        NetWorkRequest(.unread()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let d = jsonFormater(data: res["data"] as Any)
                self.navigationItem.rightBarButtonItem?.pp.addBadge(number: d["unread_count"].intValue)
            }
        }
        
        NetWorkRequest(.enterpriseinfo()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                if data["bank_is_trade"].intValue == 1 &&
                    data["base_is_trade"].intValue == 1 &&
                    data["detail_is_trade"].intValue == 1 &&
                    data["user_is_trade"].intValue == 1
                {
                    self.isRenZheng = true
                }else {
                    self.showSign("您的资料还未完善，请先完善资料？")
                }
                if data["is_ca"].intValue == 1 {
                    self.isCa = true
                    (UIApplication.shared.delegate as! AppDelegate).isCa = true
                }else {
                    self.isCa = false
                    (UIApplication.shared.delegate as! AppDelegate).isCa = false
                }
                (UIApplication.shared.delegate as! AppDelegate).enterprise_name = data["enterprise_name"].stringValue
                (UIApplication.shared.delegate as! AppDelegate).enterprise_id = data["enterprise_id"].intValue
                self.tableView.reloadData()
            }
        }
        loadBulletin()
    }
    

    
    @objc func loadBulletin() {
        
        NetWorkRequest(.bulletin(param: ["page":"1","per_page":"5"])) {[weak self] (res) -> (Void) in
            
            let resdata = jsonFormater(data: res)
            
            if resdata["code"].stringValue == "000000" {
                self?.bulletinData = JSON(resdata["data"])["data"].arrayValue as NSArray
                self?.tableView.reloadData()
            }
        }
        NetWorkRequest(.banner()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let jd = JSON(res["data"]!)["ads"].arrayValue as NSArray
                self.bannerData = jd
                self.adView.reloadData()
            }
        }
        
    }
    
    @objc func openMessage(_ bar : UIBarButtonItem) {
        let vc = R.storyboard.user.messageViewController()!
        vc.type = 1
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func showGongG(_ sender: UIButton) {
        let vc = R.storyboard.user.messageViewController()!
        vc.type = 2
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func imageUrl(_ url:NSURL, image: UIImage) {
        
    }
    
    func bannerViewImages(_ bannerView: YJBannerView!) -> [Any]! {
        
        if self.bannerData.count > 0 {
            
            let data:NSMutableArray = []
            
            for d in self.bannerData {
                let jd = JSON(d)
                data.add(jd["creative_url"].stringValue)
            }
            return data as? [Any]
        }
        return ["http://file.gllive.net/banner.png"]
    }
    
    func bannerView(_ bannerView: YJBannerView!, didSelectItemAt index: Int) {
        let web = WebViewController()
        web.urlArr = ["http://www.grain.cq.cn"]
        self.navigationController?.pushViewController(web, animated: true)
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bulletinData.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeTableViewCell", for: indexPath) as! HomeTableViewCell
        let data = bulletinData[indexPath.row] as! JSON
        cell.labelTitle.text = data["title"].stringValue
        cell.labelDate.text = data["created_at"].stringValue
        
        cell.imgRead.isHidden = data["read_status"].boolValue
        
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let data = bulletinData[indexPath.row] as! JSON
        
        NetWorkRequest(.bulletin_id(id:data["id"].stringValue)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let vc = MsgDescViewController()
                vc.bulletin_id = data["id"].stringValue
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
//        let vc = MsgDescViewController()
//        vc.bulletin_id = data["id"].stringValue
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func showSign(_ content:String, _ b:Bool = false) -> Void {
        
        if b == true {
            UIAlertController.showAlert(in: self, withTitle: "温馨提示", message: content, cancelButtonTitle: "确定", destructiveButtonTitle: nil, otherButtonTitles: nil, tap: { (vc, ac, index) in
            })
        }else {
            UIAlertController.showAlert(in: self, withTitle: "温馨提示", message: content, cancelButtonTitle: "取消", destructiveButtonTitle: "确定", otherButtonTitles: nil, tap: { (vc, ac, index) in
                if index > 0 {
                    self.navigationController?.pushViewController(R.storyboard.user.userBaseViewController()!, animated: true)
                }
            })
        }
    }
    
    @IBAction func buy(_ sender: UIButton) {
        
        if self.isRenZheng == false {
            self.showSign("您的资料还未完善，请先完善资料？")
            return
        }
        
        showHUD()
        NetWorkRequest(.enterpriseinfo()) { (res) -> (Void) in
            dismissHUD()
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                if data["bank_is_trade"].intValue == 1 &&
                    data["base_is_trade"].intValue == 1 &&
                    data["detail_is_trade"].intValue == 1 &&
                    data["user_is_trade"].intValue == 1
                {
                    self.isRenZheng = true
                }else {
                    self.showSign("您的资料还未完善，请先完善资料？")
                }
                if data["is_ca"].intValue == 1 {
                    self.isCa = true
                    (UIApplication.shared.delegate as! AppDelegate).isCa = true
                }else {
                    self.isCa = false
                    (UIApplication.shared.delegate as! AppDelegate).isCa = false
                }
                
                
                if self.isCa == false {
                    
                    
                    
                    self.showSign("实名未完成，请先实名", true)
                    return
                }
                
                let vc = HomeView.showView(frame:self.view.bounds)
                self.view.addSubview(vc)
                vc.nav = self.navigationController
                
                (UIApplication.shared.delegate as! AppDelegate).isBuy = 0
                
                vc.ob = {(res) -> Void in
                    BuyViewController.defalut.direction = 2
                    self.navigationController?.pushViewController(R.storyboard.home.buyViewController()!, animated: true)
                }
                vc.can = {(res) -> Void in
                    UIAlertController.showAlert(in: self, withTitle: "温馨提示", message: "请尽早阅读《交易规则》，当期《交易公告》", cancelButtonTitle: "确定", destructiveButtonTitle: nil, otherButtonTitles: nil, tap: { (vc, ac, index) in
                    })
                }
                
                
            }
        }
        
        
        
    }
    
    @IBAction func post(_ sender: UIButton) {
        if self.isRenZheng == false {
            self.showSign("您的资料还未完善，请先完善资料？")
            return
        }
        
        
        showHUD()
        NetWorkRequest(.enterpriseinfo()) { (res) -> (Void) in
            dismissHUD()
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                if data["bank_is_trade"].intValue == 1 &&
                    data["base_is_trade"].intValue == 1 &&
                    data["detail_is_trade"].intValue == 1 &&
                    data["user_is_trade"].intValue == 1
                {
                    self.isRenZheng = true
                }else {
                    self.showSign("您的资料还未完善，请先完善资料？")
                }
                if data["is_ca"].intValue == 1 {
                    self.isCa = true
                    (UIApplication.shared.delegate as! AppDelegate).isCa = true
                }else {
                    self.isCa = false
                    (UIApplication.shared.delegate as! AppDelegate).isCa = false
                }
                
                
                if self.isCa == false {
                    self.showSign("实名未完成，请先实名", true)
                    return
                }
                
                
                (UIApplication.shared.delegate as! AppDelegate).isBuy = 1
                let vc = HomeView.showView(frame:self.view.bounds)
                self.view.addSubview(vc)
                vc.nav = self.navigationController
                vc.ob = {(res) -> Void in
                    
                    BuyViewController.defalut.direction = 1
                    self.navigationController?.pushViewController(R.storyboard.home.buyViewController()!, animated: true)
                }
                vc.can = {(res) -> Void in
                    UIAlertController.showAlert(in: self, withTitle: "温馨提示", message: "请尽早阅读《交易规则》，当期《交易公告》", cancelButtonTitle: "确定", destructiveButtonTitle: nil, otherButtonTitles: nil, tap: { (vc, ac, index) in
                        
                    })
                }
                
            }
        }
        
        
//        if self.isCa == false {
//            self.showSign("实名未完成，请先实名", true)
//            return
//        }
        
        
    }
    
}

